import { AxiosRequestConfig, AxiosResponse } from 'axios'
import axios from './axios'
import { isEmpty } from '@/utils/common'
import { history } from 'umi';
import { Message } from '@/design'
import { parse } from 'search-params'

function checkStatus(response: AxiosResponse) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }

  const error: any = new Error(response.statusText);
  error.response = response;
  throw error;
}

function clearUserLoginState(noLogin?:boolean) {
  localStorage.removeItem('userInfo'); // 清除token缓存
  if (history.location.pathname === '/line') return;
  !noLogin && history.push('/line');
}


const exceptionHandle = (error:any) => {
  const { response } = error;
  if (!response) {
    Message.error('您的網絡發生異常，無法連接服務器');
  } else {
    switch (response.status) {
      case 401:
        // console.log(response)
        if (Number(response.data.code) === 407) {
          localStorage.removeItem('userInfo'); // 清除token缓存
          history.push('/line');
        // } else {
        //   Toast.offline('权限受限，请向管理员申请后重试' , 2, null, false);
        }
        clearUserLoginState();
        break;
      case 404:
        history.push('/exception/404');
        break;
      case 500:
        // history.push('/exception/500');
        if (Number(response.data.code) === 407 || Number(response.data.code) === 888) {
          localStorage.removeItem('TOKEN'); 
          localStorage.removeItem('userInfo'); // 清除token缓存
          window.location.reload();
          return false;
          // history.push('/line');
          // window.location.reload();
          // return false;
        // } else {
        //   Toast.offline('权限受限，请向管理员申请后重试' , 2, null, false);
        }
        Message.error('您的網絡發生異常，無法連接服務器');
        
        break;
      case 502:
        // history.push('/exception/500');
        Message.error('您的網絡發生異常，無法連接服務器');
        break;
      case 407:
        console.log('進來')
        localStorage.removeItem('userInfo'); // 清除token缓存
        localStorage.removeItem('TOKEN');
        history.push('/line');
        break;
      default:
        break;
    }
  }
};

export const request = async (url: string, options?: AxiosRequestConfig, noLogin?: boolean) => {
  // console.log(1)
  let token = localStorage.getItem('TOKEN');
  let userInfo: any = localStorage.getItem('userInfo');
  const { braId } = parse(window.location.search)
  if (isEmpty(userInfo)) {
    // 如果用户信息为空
    userInfo = '{}';
  }
  let axiosConfig: AxiosRequestConfig = {
    url,
    method: 'GET',
    timeout: 20000,
    headers: {
      'Content-Type': 'application/json',
      'Token': token,
      'Buy-Flag': !isEmpty(localStorage.getItem("userInfo") )? 'umeMember' : 'trendlabstore.cn' ,//登录的情况下传umemember否则就传trendlabstore.cn
      'Request-Tk': token || undefined,
      'merId': '',
      'Platform': 'web',
      'braId': braId || localStorage.getItem("BRAID"),
      'Bra-Id':  braId || localStorage.getItem("BRAID"),
    },
    ...options,
  };

  /* 发起请求 */
  return axios(axiosConfig)
  .then(checkStatus)
  .then(res => {
    const result = res.data;
    const resultCode = Number(result.code);
      if (resultCode !== 200) {
        /* 请求成功但返回数据失败 */
        if (resultCode === 401) {
          /* 权限受限 */
          Message.error(result.message || '權限受限');
          // !noLogin && Toast.offline(result.message || '權限受限' , 2, null, false);
          clearUserLoginState(noLogin);
        } else if (resultCode === 407) {
          /* 登录超时或多地登陆 */
          console.log('進來2')
          Message.error(result.message || '登入已失效');
          history.push('/line')
          clearUserLoginState(noLogin);
        } else {
          /* 其它异常 */
          console.log('其他异常', 112)
          Message.error(result.message || '請求響應異常');
        }
        return false;
      } 
    return res.data
  }).catch(err => {
    console.log(err)
    exceptionHandle(err)
    return false
  })
}
